const { ref, computed, watch } = Vue
import selectall from './SelectAll.js'
import productitem from './ProductItem.js'

export default {
    props: {
        list: {
            type: Array
        }
    },
    setup(props) {
        const list = ref(props.list)
        const isAllCheck = ref(false)
        const totalPrice = ref(0)
        const checkedCount = ref(0)
        watch(list, () => {
            const total = list.value.reduce((sum, item) => sum + (item.checked ? item.price * item.num : 0), 0)
            totalPrice.value = total.toFixed(2)
            checkedCount.value = list.value.filter(item => item.checked).length
            isAllCheck.value = list.value.every(item => item.checked)
        })
        const toggleSelectAll = (val) => {
            list.value.forEach(item => {
                item.checked = val
            })
        }
        const updateNum = (num, index) => {
            list.value[index].num = num;
        };
        const updateChecked = (checked, index) => {
            list.value[index].checked = checked
        }
        const removeItem = (item) => {
            list.value.splice(list.value.indexOf(item), 1)
        }
        return {
            list,
            isAllCheck,
            totalPrice,
            checkedCount,
            toggleSelectAll,
            updateNum,
            updateChecked,
            removeItem
        }
    },
    template: `#productlist`
}